/*
 * @Author: qf
 * @Date: 2021-05-12 18:31:50
 * @LastEditTime: 2021-07-21 16:45:56
 * @LastEditors: qf
 * @Description:
 */
import store from '@/store'
import router from '@/router'

const getUuid = () => {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

const getShortUuid = () => {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 32; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  var uuid = s.join('')
  return uuid
}

export function deepClone(data) {
  var type = getObjType(data)
  var obj
  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    // 不再具有下一层次
    return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key])
    }
  }
  return obj
}

export function getObjType(obj) {
  var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[toString.call(obj)]
}

export function getButtonAttribute(key, type, name) {
  var buttonArray = {
    'read': {
      name: '查看',
      type: 'primary'
    },
    'update': {
      name: '编辑',
      type: 'warning'
    },
    'delete': {
      name: '删除',
      type: 'danger'
    },
    'create': {
      name: '新增',
      type: 'primary',
      icon: 'el-icon-plus'
    },
    'export': {
      name: '导出',
      type: 'warning',
      icon: 'el-icon-download'
    },
    'import': {
      name: '导入',
      type: 'warning',
      icon: 'el-icon-upload2'
    },
    'closeCurRoute': {
      name: '关闭当前页'
    }
  }
  if (name) {
    return name
  } else if (buttonArray[key]) {
    if (buttonArray[key][type]) {
      return buttonArray[key][type]
    } else {
      return ''
    }
  } else {
    if (type === 'type') {
      return 'danger'
    } else if (type === 'name') {
      return '默认'
    } else {
      return ''
    }
  }
}

/*
thisInstance this对象
deleteMethod  删除方法
params 数组 要删除的id的数组
*/
export function deleteMethod(thisInstance, deleteMethod, params, titleName) {
  let that = thisInstance
  let name = titleName || '删除'
  return new Promise((resolve, reject) => {
    if (getObjType(params) === 'object' || params.length > 0) {
      that.$confirm('确定' + name + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = name + '中...'
            deleteMethod(params).then((res) => {
              instance.confirmButtonLoading = false
              done()
              that.$message.success(name + '成功')
              resolve(res)
            }).catch((err) => {
              instance.confirmButtonText = '确定'
              instance.confirmButtonLoading = false
              reject(err)
            })
          } else {
            done()
          }
        }
      })
    } else {
      that.$message.error('至少选择一条数据')
    }
  })
}

export function getCurrentSchoolId() {
  // 如果当前用户只有一个学校，需要获取当前学校的id并进行默认赋值
  let schoolList = this.$store.state.user.schoolList
  if (schoolList && schoolList.length === 1) {
    return schoolList[0].schoolId
  } else {
    return ''
  }
}

// 通用的文件下载
export function exportFile(res, type, name) {
  let fileType = ''
  if (type === 'zip') {
    fileType = 'application/zip'
  } else if (type === 'xls') {
    fileType = 'application/vnd.ms-excel'
  }
  var url = window.URL.createObjectURL(new Blob([res], { type: fileType }))
  var aLink = document.createElement('a')
  aLink.style.display = 'none'
  aLink.href = url
  aLink.setAttribute('download', name + '.' + type)
  document.body.appendChild(aLink)
  aLink.click()
  document.body.removeChild(aLink)
  window.URL.revokeObjectURL(url)
}

/**
 * @description: 关闭当前路由
 * @param {*} curRoute 当前路由
 * @param {*} backRoute 需返回路由
 * @return {*}
 */
export function closeCurRoute(curRoute, backRoute, query) {
  store.dispatch('tagsView/delView', curRoute)
  if (backRoute) {
    router.push({ name: backRoute, query })
  } else {
    router.back()
  }
}

export { getUuid, getShortUuid }
